from django.http import HttpResponse, HttpRequest
from django.shortcuts import render

import os
import json

from .Helper import getDefaultContext2, detectImage, getContextResult, \
    round_floats, getContextResults2, getSaveImagePath, getNoFileDetectResult

def index(request):##跳转到登陆界面 测试用
    return render(request, 'myweb/test2.html')
    # return HttpResponse('Hello World!')

## 进入新的 批量检测的网页 2023-12-23
def testBatch(request):
    return render(request, 'myweb/detectImages.html')

## 处理单个文件上传
def uploadFiles(request):
    bFile, image_path, file_name = saveUploadFile(request)
    context = {
        'bFile' : bFile,
        'image_path' : image_path,
        'file_name' : file_name
    }
    print(image_path)
    return HttpResponse(json.dumps(context))

## 单个保存上传文件的实际处理，以后要改为分块上传保存 chrunk，根军fileinput组件的上传优化
def saveUploadFile(request):
    bFile = False

    file = request.FILES.get("fileBlob", None)
    fileSize = request.POST.get('fileSize', '0')
    fileSize = int(fileSize)

    chunkCount = int(request.POST.get("chunkCount", '0'))
    chunkIndex = int(request.POST.get("chunkIndex", '0'))
    chunkSize = int(request.POST.get("chunkSize", '0'))
    chunkSizeStart = int(request.POST.get("chunkSizeStart", '0'))
    ## 后面再加上分块上传的功能


    if file is None: #or fileSize <= 10: #针对enableResumableUpload=false没有默认传递fileSize
        return bFile, '',  ''

    image_path = getSaveImagePath(file.name)#获取保存路径

    with open(image_path, 'wb+') as f:
        # 分块写入文件;
        for chunk in file.chunks():
            f.write(chunk)

    bFile = True
    return bFile, image_path, file.name


##获得上传文件的数据
def isUploadFilesReady(request):
    if request.method != "POST":
        print('fileUpload.py : isUploadFileReady, request.method != POST.............')
        return False, ''

    strData = request.POST.get('batch_data', '')
    print('-------request(batch_data)', strData)
    if strData == '':
        return False, None
    try:
        data = json.loads(strData)
    except Exception as e:
        print(e, type(e))
        return False, None
    else:
        return True, data


# 批量检测图片结果，并返回JSON 2023-12-22
def detectBatchImages(request):
    action = request.POST.get('action', None)
    print('uploadDetect:', action)
    if action == 'ajax':
        return detectBatchAjax(request)
    else:
        return testAjax(request)

# 用作测试，简单返回文件作为处理
def testAjax(request):
    fileName = 'static/test-batch.json'
    fileName = os.path.join(os.getcwd(), fileName).replace('\\', '/')
    print(fileName)
    data = ''
    with open(fileName, 'r', encoding = "utf-8") as f:
        data = f.read()
    #print('data:', data)
    return HttpResponse(data)

# 批量检测图片结果
def detectBatchAjax(request):
    bFile, imagess = isUploadFilesReady(request)
    if bFile == False:
        context = getDefaultContext2()
        return HttpResponse(json.dumps(context))

    nDetect = 0
    isImg = False
    context = []
    for image in imagess:
        print('--------image:', image)
        width = image['width']
        height = image['height']

        fileName = image['fileName']
        image_path = getSaveImagePath(fileName)  # 获取保存路径
        if os.path.exists(image_path):
            data = detectImage(image_path, isImg, (int(width), int(height)))  ##调用Helper
            print('-=-=-=-=-=-=-=-=batch_detect:', image_path)
            # print('--=-=-=-=-=-=-==-=-dat*a:', data)
            result = getContextResult(*data, isImg, fileName)  ##调用Helper
            # print(':::::::::::result:', result)
            nDetect += 1
        else:
            result = getNoFileDetectResult(image_path, fileName)
            print(':::::::::::No File Detect:', image_path)
        context.append(result)

    ret = getContextResults2(context, nDetect, len(imagess))
    return HttpResponse(json.dumps(round_floats(ret)))

